package com.hlkj.baojin.dao.repository;

import com.hlkj.baojin.constant.BaojinConstant;
import com.hlkj.baojin.constant.BaseRepository;
import com.hlkj.baojin.entity.CompanyArea;
import com.hlkj.baojin.entity.dto.CompanyAreaSearchDto;
import com.hlkj.baojin.entity.dto.ModelList;
import com.hlkj.baojin.utils.PatternUtil;
import com.hlkj.baojin.utils.bean.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author HULIN
 * @created with: baojin
 * @package com.hlkj.baojin.dao.repository
 * @description:
 * @date 2019/1/9 10:51
 * @modified By:
 * @Copyright © 2018 HAILIANG Info. Tech Ltd. All rights reserved.
 */
@Repository
public class CompanyAreaRepository extends BaseRepository<CompanyArea> {

    public CompanyAreaRepository(MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }

    public void updateDeviceNotNull(CompanyArea companyArea) {
        CompanyArea companyAreaDB = new CompanyArea();
        companyAreaDB.setId(companyArea.getId());
        super.updateByBean(companyAreaDB, companyArea);
    }

    public ModelList<CompanyArea> getCompanyArea(CompanyAreaSearchDto companyAreaSearchDto) {
        Query query = new Query();

        if(StringUtils.isNotBlank(companyAreaSearchDto.getMultiCondition())) {
            query.addCriteria(Criteria.where("name").regex(PatternUtil.fuzzyMatch(companyAreaSearchDto.getMultiCondition())));
        }

        if(companyAreaSearchDto.getType() != null) {
            query.addCriteria(Criteria.where("type").is(companyAreaSearchDto.getType()));
        }
        if(StringUtils.isNotBlank(companyAreaSearchDto.getDeptId())) {
            query.addCriteria(Criteria.where("belongCompany").is(companyAreaSearchDto.getDeptId()));

        }
        query.addCriteria(Criteria.where("delete").is(BaojinConstant.IS_NO_DELETE));

        query.with(new Sort(Sort.Direction.DESC, "createTime"));
        query.with(new Page(companyAreaSearchDto.getPage(), companyAreaSearchDto.getSize()));

        List<CompanyArea> companyAreaList = mongoTemplate.find(query, CompanyArea.class);
        long count = mongoTemplate.count(query, CompanyArea.class);

        ModelList<CompanyArea> companyAreaModelList = new ModelList<>(companyAreaList, count);

        return companyAreaModelList;
    }

}
